<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie-Test</title>
</head>
<body>
	<%! 
		int count = 0;
	
		public void jspInit() {
		   System.out.println("JSP Inited");
		}
		public void jspDestroy() {
		   System.out.println("JSP Destroyed");
		}
		public void _jspService() {
		   System.out.println("SERVICE DAYO!");
		}
	%>
	<%= "Page accessed " + ++count + " times." %>
	<%
		String enteredName = request.getParameter("enteredName");
		if(enteredName == null) {
		   Cookie[] cookies = request.getCookies();
			boolean found = false;
			String uName = null;
			if(cookies != null) {
				for(Cookie cookie : cookies) {
				   if(cookie.getName().equals("uname")) {
				      found = true;
				      uName = cookie.getValue();
				      break;
				   }
				}
			}
			if(found) {
			   out.println("<br/>Hello " + uName + "! Welcome back :-)");
			} else {
			   out.println("<br/>Please enter your name: <form action='cookie-test.jsp'><input type='text' name='enteredName' /><br /><input type='submit' /></form>");
			}
		} else {
		   Cookie nameCookie = new Cookie("uname", enteredName);
		   nameCookie.setMaxAge(60 * 2);
		   response.addCookie(nameCookie);
		   response.encodeRedirectURL("cookie-test.jsp");
		}
	%>
	<div>${1+2}</div>
</body>
</html>